import axios from 'axios'
import { useUserStore } from '../stores'
import { ElMessage } from 'element-plus'
// import { useRouter } from 'vue-router'
import router from '../router'
// const router = useRouter()
const baseURL = 'http://big-event-vue-api-t.itheima.net'
// 1.基地址和超时时间
const instance = axios.create({
  baseURL,
  timeout: 1000000
})
instance.interceptors.request.use(
  function (config) {
    // 2.token携带
    const userStore = useUserStore()
    if (userStore.token) {
      // config.headers.Authorization = 'Bearer' + userStore.token
      config.headers.Authorization = userStore.token
    }
    return config
  },
  function (error) {
    return Promise.reject(error)
  }
)

// 添加响应拦截器
instance.interceptors.response.use(
  function (response) {
    if (response.data.code === 0) {
      return response
    } else {
      // 3.业务失败
      ElMessage.error(response.data.message || '服务器异常')
      return Promise.reject(response.data)
    }
  },
  function (error) {
    ElMessage.error({ message: error.response?.data.message || '服务异常' })
    // 4.处理401错误
    if (error.response?.status === 401) {
      router.push('/login')
    }
    // ElMessage.error('服务器异常')
    return Promise.reject(error)
  }
)
export default instance
export { baseURL }
